<template>

  <div class="login-container">
    <div class="login-box">
      <SwitchDark class="login-dark" />
      <div class="login_wrap">
        <div class="login_form">
          <div class="form_lt"></div>
          <div class="form_rt">
            <div class="login-logo">
              <img class="img" :src="setting.logo" />
            </div>
            <div class="form_title">
              <!--后端logo      -->
              {{ setting.title }}
            </div>
            <el-form
              ref="ruleFormRef"
              :model="loginForm"
              :rules="rules"
              label-width="0px"
              status-icon
              class="form_box"
            >
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  show-password
                  prefix-icon="Lock"
                />
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled" class="item-code">
                <div style="width: 100%;">
                  <el-input
                    v-model="loginForm.code"
                    auto-complete="off"
                    placeholder="验证码"
                    style="width: 65%;  float: left;"
                    @keyup.enter.native="submitForm(ruleFormRef)"
                  >
                    <template #prefix>
                      <SvgIcon iconClass="validCode" />
                    </template>
                  </el-input>

                  <div class="login-code" style="float: right; background-color: #0000ff">
                    <img :src="codeUrl" @click="getCode" class="login-code-img" />
                  </div>
                </div>

                <!--                <el-input
                                  v-model="loginForm.code"
                                  auto-complete="off"
                                  placeholder="验证码"
                                  style="width: 60%;  float: right;"
                                  @keyup.enter.native="submitForm(ruleFormRef)"
                                >
                                  <template #prefix>
                                    <SvgIcon iconClass="validCode" />
                                  </template>
                                </el-input>

                                <div class="login-code" style="float: right;">
                                  <img :src="codeUrl" @click="getCode" class="login-code-img" />
                                </div>-->
              </el-form-item>
            </el-form>
            <div class="login_remember">
              <el-checkbox v-model="loginForm.rememberMe" label="记住密码7天" style="float: left" />
              <router-link class="linktype" :to="{ path: '/register' }" style="float: right">立即注册</router-link>
            </div>
            <div class="login_btn">
              <el-button :loading="loading" type="primary" @click="submitForm(ruleFormRef)">
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import setting from "../../setting.ts";
import { ElMessageBox, ElNotification, FormInstance, FormRules } from "element-plus";
import Particle from "@/components/Particles/index.vue";
import { reqCodeUrl } from "@/api/user/index.ts";
import { getTime } from "@/utils/time";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/store/modules/user.ts";
import { decrypt, encrypt } from "@/utils/jsencrypt.ts";
import SvgIcon from "@/components/SvgIcon/index.vue";
import Cookies from "js-cookie";
import SwitchDark from "@/components/SwitchDark/index.vue";


let UserStore = useUserStore(); /*获取useStore仓库*/
let $router = useRouter(); /*获取路由器*/
let $route = useRoute(); /*获取路由对象*/

/*表单绑定*/
const ruleFormRef = ref<FormInstance>(null);
/*是否开启验证码*/
const captchaEnabled = ref(true);
/*表单*/
const loginForm = reactive({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});
/*验证规则*/
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "change" }],
  password: [
    { required: true, message: "请输入密码", trigger: "change" },
    { min: 6, max: 20, message: "长度应为6-20", trigger: "blur" }
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "change" }]
});
/*验证码路径*/
const codeUrl = ref();
/*登录按钮等待加载*/
const loading = ref(false);

//登录
const submitForm = async (formEl: FormInstance | undefined) => {
  /*先对表单进行验证*/
  if (!formEl) return;
  /*valid参数是一个布尔值，用于表示表单的验证结果。如果表单验证通过，则valid为true，否则为false。
fields参数是一个包含表单字段的对象。该对象中的每个属性对应一个表单字段的名称，值是该字段的值。在回调函数中，你可以使用fields对象来访问和处理表单字段的值。*/
  loading.value = true; /*开始加载*/
  await formEl
    .validate(async (valid: any, fields: any) => {
      if (valid) {
        /*用户名密码登录*/
        await userNameLogin();
      } else {
        console.log("error submit!");
      }
    })
    .catch(() => {
    });
};

/*用户名密码登录*/
const userNameLogin = async (formEl: FormInstance | undefined) => {
  /*进行登录操作*/
  try {
    await UserStore.userLogin(loginForm);
    console.log("登录成功");
    /*进行路由跳转*/
    /*编程式导航跳转到首页*/
    /*判断query是否有*/
    let redirect = $route.query.redirect;
    /*有redirect就跳到该目录，没有跳到首页*/
    await $router.push({ path: redirect || "/" });
    ElNotification({
      type: "success",
      message: "登录成功",
      title: "Hi," + getTime() /*判断是什么时间*/
    });
  } catch (error) {
    loading.value = false;
    ElNotification({
      type: "error",
      message: (error as Error).message
    });
    if (captchaEnabled.value) {
      await getCode();
    }
  }
  setCookie(loginForm);
};

/**
 * 获取Cookie信息
 */
const getCookie = () => {
  const username = Cookies.get("username-yixia");
  const password = Cookies.get("password-yixia");
  const rememberMe = Cookies.get("rememberMe-yixia");
  loginForm.username = username === undefined ? loginForm.username : username;
  loginForm.password = password === undefined ? loginForm.password : decrypt(password);
  loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
};

/*存到cookie*/
const setCookie = (loginForm: any) => {
  /*将数据存储到本地*/
  if (loginForm.rememberMe) {
    /*expires是过期时间30表示30天*/
    Cookies.set("username-yixia", loginForm.username, { expires: 7 });
    Cookies.set("password-yixia", encrypt(loginForm.password), { expires: 7 });
    Cookies.set("rememberMe-yixia", loginForm.rememberMe, { expires: 7 });
  } else {
    Cookies.remove("username-yixia");
    Cookies.remove("password-yixia");
    Cookies.remove("rememberMe-yixia");
  }
};

/*获取验证码*/
const getCode = async () => {
  const result = await reqCodeUrl();
  if (result.code === 200) {
    codeUrl.value = "data:image/gif;base64," + result.img;
    captchaEnabled.value = result.captchaEnabled;
    if (result.captchaEnabled) {
      loginForm.uuid = result.uuid;
      loginForm.code = "";
    }
  } else {
    await ElMessageBox({
      type: "error",
      message: result.message != null ? result.message : "获取验证码失败！"
    });
  }
};

onMounted(() => {
  getCode();
  getCookie();
});
</script>

<style lang="scss" scoped>
@import './index';

.login_wrap {
  position: relative;
  /* background-color: #e5e5e5;
 background-image: url('@/assets/images/lgin_bg.png');
 background-repeat: no-repeat;
 background-size: 100% 100%;*/

  .login_form {
    position: absolute;
    top: 50%;
    width: 900px;
    height: 500px;
    left: 50%;
    background-image: url('@/assets/image/login/login_form.png');
    background-size: 100% auto;
    background-repeat: no-repeat;
    transform: translate3d(-50%, -50%, 0);
    display: flex;
    border-radius: 20px;

    .form_lt {
      flex: 1;
      background-image: url('@/assets/image/login/login_left.png');
      background-size: contain; /* 或者使用 contain 或 cover */
      background-repeat: no-repeat;
      margin: 60px 0 0 60px;
    }

    .form_rt {
      flex: 1;
      margin: 40px 40px;
      position: relative;

      .login-logo {
        color: black;
        width: 100%;
        text-align: center;
        margin-bottom: 20px;

        img {
          width: 73px;
          height: 50px;
        }
      }

      .form_title {
        color: #444;
        font-weight: bold;
        font-size: 20px;
        text-align: center;
        align-items: center; /*元素对齐*/
      }

      .form_box {
        padding: 60px 0 0 40px;
        width: 340px;

        .login-code-img {
          height: 38px;
        }

        .item-code {
          align-items: center;

          .login-code {

            height: 38px;

            img {
              cursor: pointer;
              vertical-align: middle;
            }
          }
        }
      }

      .login_remember {
        width: 340px;
        position: relative;
        left: 40px;
        display: flex;
        text-align: center;
        justify-content: space-between;

        .linktype {
          color: #337ab7;
          cursor: pointer;
          text-decoration: none;
          margin-top: 6px;

          &:hover {
            color: rgb(32, 160, 255);
          }
        }
      }

      .login_btn {
        padding: 10px 0 0 40px;
        width: 340px;

        .el-button {
          width: 100%;
        }
      }
    }

    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

.el-input {
  height: 38px;
}
</style>
